package com.xhsj.user.pms.patent.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import com.google.common.collect.Maps;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.pms.base.BaseController;
import com.xhsj.user.pms.patent.domain.*;
import com.xhsj.user.pms.patent.mapper.*;
import com.xhsj.user.pms.patent.query.PatentFindPatentListQuery;
import com.xhsj.user.pms.patent.service.PatentService;
import com.xhsj.user.pms.patent.service.TbPamJudgesIprService;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 专利管理
 *
 * @author suxiaolin
 * @date 2020/3/11 14:30
 */
@Slf4j
@RestController
@RequestMapping("/patent")
@CrossOrigin(origins = "*", maxAge = 3600)
public class PatentController extends BaseController {

    @Autowired
    private PatentService patentService;

    @Autowired
    private PatentMapper patentMapper;

    @Autowired
    private PatentInspectionMapper patentInspectionMapper;

    @Autowired
    private TbGlobalUserMapper userMapper;
    @Autowired
    private JudgesMapper judgesMapper;
    @Autowired
    private JudgesUserMapper judgesUserMapper;

    @Autowired
    private TbPamJudgesIprService tbPamJudgesIprService;

    @Autowired
    private DisclosureMapper disclosureMapper;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存系统流程专利", notes = "保存系统流程专利")
    public Message save(@RequestBody Map<String, Object> param) {

        try {
            log.info("保存系统流程专利参数，{}", param);
            patentService.save(param);
            return Message.success("成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1, e.getMessage());
        }
    }


    @RequestMapping(value = "/saveAlreadyExistingPatent", method = RequestMethod.POST)
    @ApiOperation(value = "保存已有的专利", notes = "保存已有的专利")
    public Message saveAlreadyExistingPatent(@RequestBody Map<String, Object> param) {

        try {
            log.info("保存已有的专利参数，{}", param);
            int save = patentService.saveAlreadyExistingPatent(param);
            if (save > 0) {
                return Message.success("成功");
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                log.error("保存失败,保存返回值为0");
                return Message.error(1, "失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存失败:{}", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 查询专利文件列表
     *
     * @param
     * @return
     */
    @PostMapping("/findPatentList")
    @ApiOperation(value = "查询专利文件列表", notes = "查询专利文件列表")
    public Message findPatentList(@RequestBody PatentFindPatentListQuery param) {
        try {
            log.info("根据名称搜索获取专利申请文件参数，{}", param);
            IPage<Map<String, Object>> list = patentService.findPatentList(param);
            return Message.success("成功",list.getRecords(),list.getTotal(),list.getPages());
        } catch (Exception e) {
            log.error("错误信息", e);
            return Message.error(1, "失败");
        }
    }


    /**
     * 查询专利文件列表
     *
     * @param
     * @return
     */
    @PostMapping("/findPiePatentList")
    @ApiOperation(value = "通过饼状图查询专利文件列表", notes = "通过饼状图查询专利文件列表")
    public Message findPiePatentList(@RequestBody PatentFindPatentListQuery param) {
        try {
            log.info("通过饼状图查询专利文件列表参数，{}", param);
            IPage<Map<String, Object>> list = patentService.findPiePatentList(param);
            return Message.success("成功",list.getRecords(),list.getTotal(),list.getPages());
        } catch (Exception e) {
            log.error("错误信息", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 二级报表查询专利文件列表
     *
     * @param
     * @return
     */
    @PostMapping("/findPatentListPie")
    @ApiOperation(value = "查询专利文件列表", notes = "查询专利文件列表")
    public Message findPatentListPie(@RequestBody PatentFindPatentListQuery param) {
        try {
            log.info("根据名称搜索获取专利申请文件参数，{}", param);
            IPage<Map<String, Object>> list = patentService.findPatentListPie(param);
            return Message.success("成功", list.getRecords(),list.getTotal(),list.getPages());
        } catch (Exception e) {
            log.error("错误信息", e);
            return Message.error(1, "失败");
        }
    }


    /**
     * 查询专利文件
     *
     * @param
     * @return
     */
    @PostMapping("/findList")
    @ApiOperation(value = "查询专利文件", notes = "查询专利文件")
    public Message findList(@RequestBody Map<String, Object> param) {
        try {
            log.info("根据名称搜索获取专利申请文件参数，{}", param);
            IPage<Patent> list = patentService.findList(param);
            return Message.success("成功", list.getRecords(),list.getTotal(),list.getPages());
        } catch (Exception e) {
            log.error("错误信息", e);
            return Message.error(1, "失败");
        }
    }

    @GetMapping("/getByNum")
    @ApiOperation(value = "通过内部编号查询专利", notes = "通过内部编号查询专利")
    public Message getByNum(@RequestParam("num") String num) {

        Patent patent = patentMapper.getByNum(num);
        return Message.success("成功", patent);
    }

    /**
     * 获取专利考核线数据
     *
     * @author 苏小林
     * @date 2020/4/8 9:36
     */
    @PostMapping("/getInspectionList")
    @ApiOperation(value = "获取专利考核线数据", notes = "获取专利考核线数据")
    public Message getInspectionList(@RequestBody Map<String, Object> param) {
        try {
            int pageNum = 1;
            int pageSize = 20;
            if (StringUtils.isNotNull(param.get("pageNum"))) {
                pageNum = Integer.parseInt(String.valueOf(param.get("pageNum")));
            }
            if (StringUtils.isNotNull(param.get("pageSize"))) {
                pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
            }
            Page<PatentInspection> page = new Page(pageNum, pageSize);
            IPage<PatentInspection> list = patentInspectionMapper.findList(page);
            return Message.success("成功",list.getRecords(),list.getTotal(),list.getPages());
        } catch (NumberFormatException e) {
            log.error("错误信息", e);
            return Message.error(1, "失败");
        }
    }

    @GetMapping("/delInspectionById")
    @ApiOperation(value = "删除考核线", notes = "删除考核线")
    public Message delInspectionById(@RequestParam("id") String id) {
        try {
//            patentInspectionMapper.deleteByPrimaryKey(id);
            patentInspectionMapper.deleteById(id);
            return Message.success("成功");
        } catch (Exception e) {
            log.error("错误信息", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 保存考核线数据
     *
     * @author 苏小林
     * @date 2020/4/8 9:36
     */
    @PostMapping("/saveInspection")
    @ApiOperation(value = "保存考核线数据", notes = "保存考核线数据")
    public Message saveInspection(@RequestBody PatentInspection patentInspection) {

        try {
            if (StringUtils.isBlank(patentInspection.getId())) {
                patentInspection.setId(IdGen.generateUUID());
                patentInspection.setCreatedDate(new Date());
                patentInspection.setUpdateBy(patentInspection.getCreatedBy());
                patentInspection.setUpdateTime(new Date());
                patentInspection.setDelFlag(0);
                patentInspectionMapper.insert(patentInspection);
            } else {
                patentInspection.setUpdateTime(new Date());
//                patentInspectionMapper.updateByPrimaryKey(patentInspection);
                patentInspectionMapper.updateById(patentInspection);
            }
            return Message.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1, "失败");
        }

    }

//    /**
//     * 修改状态
//     * @author 苏小林
//     * @date 2020/4/8 9:36
//     */
//    @GetMapping("/updateStatus")
//    @ApiOperation(value="修改状态",notes ="修改状态" )
//    public Message updateStatus(@RequestParam("id") String id,@RequestParam("status") Integer status) {
//
//        try {
//
//            if (status == 1) { // 使用中
//                patentInspectionMapper.updateStatus(2);
//            }
//            PatentInspection patentInspection = new PatentInspection();
//            patentInspection.setId(id);
//            patentInspection.setStatus(status); // 1使用中 2停用
//            patentInspectionMapper.updateByPrimaryKeySelective(patentInspection);
//            return Message.success("成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Message.error(1,"失败");
//        }
//
//    }

    /**
     * @param type           月季年
     * @param inspectionType 状态
     * @return
     */
    @GetMapping("/getInspectionByCycle")
    @ApiOperation(value = "考核线查询", notes = "考核线查询")
    public Message getInspectionByCycle(@RequestParam int type, int inspectionType) {
        log.info("考核线查询参数{}，{}", type, inspectionType);
//        根据周期得到审核线
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        List<Integer> listKey = new ArrayList<>();
        List<Map<String, Object>> inspectionList = patentInspectionMapper.getInspectionByCycle(type, inspectionType);
        for (Map<String, Object> inspection : inspectionList
        ) {
            listKey.add(Integer.valueOf(String.valueOf(inspection.get("significanceIdentify"))));
        }
        list.removeAll(listKey);
        for (Integer li : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("significanceIdentify", li);
            map.put("number", 0);
            inspectionList.add(map);
        }

        return Message.success("成功", inspectionList);
    }


    @ApiOperation(value = "查询评审会维护列表", notes = "查询评审会维护列表")
    @RequestMapping(value = "/findJudgesList", method = RequestMethod.POST)
    public Message findJudgesList(@RequestBody Map<String, Object> param) {

        try {
            Object domain = param.get("domain");
            int currentPage = 1;
            if (!Objects.isNull(param.get("page"))) {
                currentPage = (Integer) param.get("page");
            }
            int pageSize = 20;
            if (!Objects.isNull(param.get("size"))) {
                pageSize = (Integer) param.get("size");
            }

            Page<Judges> page = new Page(currentPage, pageSize);
            IPage<Judges> list = judgesMapper.findList(page, domain);
            return Message.success("成功", list.getRecords(), list.getTotal());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return Message.error();
        }

    }

    @ApiOperation(value = "删除评审会", notes = "删除评审会")
    @RequestMapping(value = "/delJudgesById", method = RequestMethod.GET)
    public Message delJudgesById(@RequestParam("id") String id) {

        try {
            // 判断是否有关联的交底书
            int relationDisclosure = disclosureMapper.getRelationDisclosure(id);
            if (relationDisclosure==0) {
            int i = judgesMapper.deleteById(id);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                log.error("删除失败,返回值为0");
                return Message.error(1, "删除失败");
            }
//            int i1 = judgesUserMapper.deleteByJudgesId(id);
            QueryWrapper<JudgesUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("judges_id", id);
            int i1 = judgesUserMapper.delete(queryWrapper);
            if (i1 == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                log.error("删除失败,返回值为0");
                return Message.error(1, "删除失败");
            }
            //删除技术领域对应的ipr根据技术领域的id
            tbPamJudgesIprService.deleteByJudgesId(id);
            return Message.success("删除成功");
            }
            return Message.success("有关联的案件不能删除");
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error();
        }

    }

    @ApiOperation(value = "通过id查询评审会", notes = "通过id查询评审会")
    @RequestMapping(value = "/getByJudgesId", method = RequestMethod.GET)
    public Message getByJudgesId(@RequestParam("id") String id) {
        try {
//            Judges judges = judgesMapper.getById(id);
            Judges judges = judgesMapper.selectById(id);
//            List<JudgesUser> byJudgesId = judgesUserMapper.getByJudgesId(judges.getId());

            QueryWrapper<JudgesUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("judges_id", judges.getId());

            List<JudgesUser> byJudgesId = judgesUserMapper.selectList(queryWrapper);
            List<Object> re = Lists.newArrayList();
            for (JudgesUser judgesUser : byJudgesId) {
                List<Object> list = Lists.newArrayList();
                list.add(judgesUser.getDeptId());
                list.add(judgesUser.getUserId());
                re.add(list);
            }
            judges.setUserList(re);
            //获取技术领域对应的ipr根据技术领域id
            List<String> judgesIprs = tbPamJudgesIprService.getJudgesIprs(judges.getId());
            judges.setIprList(judgesIprs);
            return Message.success("", judges);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error();
        }
    }

    @ApiOperation(value = "获取所有评审会", notes = "获取所有评审会")
    @GetMapping("/getAllJudges")
    public Message getAllJudges() {

        try {
            QueryWrapper<Judges> judgesQueryWrapper = new QueryWrapper<>();
            judgesQueryWrapper.select("id AS value", "domain AS label");
            List<Map<String, Object>> judges = judgesMapper.selectMaps(judgesQueryWrapper);
            return Message.success("", judges);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("getAllJudges 出错:", e);
            return Message.error();
        }


    }

    @ApiOperation(value = "保存评审会", notes = "保存评审会")
    @RequestMapping(value = "/saveJudges", method = RequestMethod.POST)
    public Message saveJudges(@RequestBody Map<String, Object> param) {
        try {
            patentService.saveJudges(param);
            return Message.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(1,"失败");
        }
    }


    @ApiOperation(value = "获取所有用户列表", notes = "获取所有用户列表")
    @RequestMapping(value = "/findAllUser", method = RequestMethod.GET)
    public Message findAllUser() {
        try {
            List<Map<String, String>> allUser = userMapper.getAllUser();
            return Message.success("成功", allUser);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error();
        }
    }

    @ApiOperation(value = "获取所有部门信息", notes = "获取所有部门信息")
    @RequestMapping(value = "/getAllDept", method = RequestMethod.GET)
    public Message getAllDept() {
        try {
//            departmentId
            List<Map<String, Object>> allDept = userMapper.getAllDept();
            List<Map<String, String>> allUser = userMapper.getAllUser();

            Iterator<Map<String, Object>> iterator = allDept.iterator();
            while (iterator.hasNext()) {
                Map<String, Object> map = iterator.next();
                Object value = map.get("value");
                if ("100".equals(String.valueOf(value))) {
                    iterator.remove();
                }
                List<Map<String, String>> ll = allUser.stream().filter(m -> {
                    Integer departmentId = StringUtils.toInteger(m.get("departmentId"));
                    boolean b = departmentId.equals(StringUtils.toInteger(value));
                    return b;
                }).collect(Collectors.toList());
                map.put("children", ll);
            }
            return Message.success("成功", allDept);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error();
        }
    }

       /**
           * @Description:  修改专利信息
           * @Param:  Map<String,Object> param
           * @return:Message
           * @Author: liuqinghua
           * @Date: 2021/2/3
           */
    @ApiOperation(value = "修改专利信息", notes = "修改专利信息")
    @PostMapping(value = "/savePatentInfo")
    public Message savePatentInfo(@RequestBody Map<String,Object> param){
     try{
        patentService.savePatentInfo(param);
       return Message.success("成功");
    } catch (Exception e) {
        e.printStackTrace();
        log.error("保存失败:{}", e);
        return Message.error(1, "失败");
    }
    }
}
